package com.llw.notify.notification;

import android.util.Log;

import com.llw.notify.mail_sender.EmailSender;
import com.llw.notify.mail_sender.EmailServer;
import com.llw.notify.setting.SettingsManager;
import com.llw.notify.util.DateFormatter;
import com.llw.notify.util.HTMLMarker;
import com.llw.notify.util.Utils;

import java.text.MessageFormat;

import javax.mail.internet.AddressException;

public class EmailSynchronizer extends Thread {
    private final String TAG = EmailSynchronizer.class.getSimpleName();

    private final String packageName;
    private final String title;
    private final String body;
    private final long postTime;

    public EmailSynchronizer(
            final String packageName,
            final String title,
            final String body,
            final long postTime) {
        this.packageName = packageName;
        this.title = title;
        this.body = body;
        this.postTime = postTime;
    }

    @Override
    public void run() {
        sendEmail(
                MessageFormat.format(
                        "{0}@{1}",
                        this.title,
                        Utils.getAppNameByPackageName(this.packageName)
                ),
                MessageFormat.format(
                        "{0}{1}{2}：{3}{4}{5}：{6}",
                        this.body,
                        HTMLMarker.LF,
                        HTMLMarker.boldRaw("通知时间"),
                        DateFormatter.datetimeSecond(this.postTime),
                        HTMLMarker.LF,
                        HTMLMarker.boldRaw("应用包名"),
                        this.packageName
                )
        );
    }

    private void sendEmail(final String title, final String content) {
        try {
            final String senderEmail = SettingsManager.getSenderEmail();
            final String senderPassport = SettingsManager.getSenderEmailPassport();
            final String senderHost = EmailServer.getEmailHost(senderEmail);
            final String senderPort = EmailServer.getEmailServerPort(senderEmail);
            final String receiverEmail = SettingsManager.getReceiverEmail();
            Log.v(TAG, "sender: " + senderEmail + ", receiver: " + receiverEmail);

            EmailSender emailSender = new EmailSender();
            emailSender.setProperties(senderHost, senderPort);
            emailSender.setMessage(senderEmail, title, content);
            emailSender.setReceiver(new String[]{receiverEmail});
            emailSender.sendEmail(senderHost, senderEmail, senderPassport);
        } catch (AddressException addressException) {
            Log.e(TAG, "邮件地址存在问题，转发失败", addressException);
        } catch (Exception e) {
            Log.e(TAG, "未知错误，请查看日志", e);
        }
    }
}
